<template>
  <div>
    <div class="box-border p-12px">
      <div>
        <SubTitle title="基本信息" />
        <el-descriptions :column="descInfo.column">
          <el-descriptions-item
            :label="item.label"
            v-for="(item, index) in descInfo.columns"
            :key="index"
          >
            <span v-if="item.key == 'fileFingerprint'">
              <el-tooltip placement="top" :content="descInfo.data.md5 || '无'">
                <span>MD5,</span>
              </el-tooltip>
              <el-tooltip placement="top" :content="descInfo.data.kfs || '无'">
                <span>KFS,</span>
              </el-tooltip>
              <el-tooltip placement="top" :content="descInfo.data.pfs || '无'">
                <span>PFS,</span>
              </el-tooltip>
              <el-tooltip placement="top" :content="descInfo.data.psa || '无'">
                <span>PSA</span>
              </el-tooltip>
            </span>
            <span v-else>{{ descInfo.data[item.key] || '--' }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <el-form ref="formRef" :rules="rules" :model="form" class="mt-12px">
        <div class="mt-16px">
          <SubTitle title="分类分级信息">
            <!-- <el-button
              link
              type="primary"
              class="ml-12px"
              @click="openSample"
              v-if="props.params.dataType !== 'schema'"
              >查看抽样数据</el-button
            > -->
          </SubTitle>
          <el-table :data="tableData" style="width: 100%">
            <el-table-column label="">
              <template #default="scope">
                <div>{{ scope.row.title }} </div>
              </template>
            </el-table-column>
            <el-table-column label="分类">
              <template #default="scope">
                <div v-if="scope.row.title === '自动生成'"
                  >{{ descInfo.data.classificationName || '' }}
                </div>
                <div v-else>
                  <el-form-item required prop="handClassification">
                    <el-cascader
                      ref="cascaderRef"
                      v-model="form.handClassification"
                      placeholder="请选择分类"
                      :props="classificationCascaderProps"
                      :options="classificationList"
                      filterable
                      clearable
                      @change="classificationChange"
                    />
                  </el-form-item>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="分级">
              <template #default="scope">
                <div v-if="scope.row.title === '自动生成'"
                  >{{ descInfo.data.levelName || '' }}
                </div>
                <div v-else>
                  <el-form-item required prop="handLevel">
                    <el-select v-model="form.handLevel" placeholder="请选择">
                      <el-option
                        v-for="item in levelList"
                        :key="item.levelCode"
                        :label="item.levelName"
                        :value="item.levelCode"
                      />
                    </el-select>
                  </el-form-item>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="重要程度">
              <template #default="scope">
                <div v-if="scope.row.title === '手动调整'">{{
                  form.handImportance || '重要数据'
                }}</div>
                <div v-else>重要数据</div>
              </template>
            </el-table-column>
          </el-table>
          <div class="mt-12px w-100% text-right">
            <el-text>
              <el-icon>
                <Warning />
              </el-icon>
              若手动调整，则最终分类分级以手动调整后的结果为准
            </el-text>
          </div>

          <el-form-item label="敏感期限" required prop="sensitiveDeadline">
            <el-radio-group v-model="form.sensitiveDeadline">
              <el-radio label="1" key="1">默认期限</el-radio>
              <el-radio label="2" key="2">指定期限</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-row>
            <el-form-item
              label="期限时间"
              required
              prop="deadlineTimeNum"
              v-if="form.sensitiveDeadline === '2'"
            >
              <ns-input
                v-model="form.deadlineTimeNum"
                clearable
                type="number"
                placeholder="请输入整数时长"
                class="flex-1"
              />
            </el-form-item>
            <el-form-item required prop="deadlineTimeUnit" v-if="form.sensitiveDeadline === '2'">
              <el-select
                v-model="form.deadlineTimeUnit"
                placeholder="请选择时间单位"
                class="ml-12px flex-1"
              >
                <el-option
                  v-for="item in timeUnitOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-row>

          <el-form-item
            label="到期后敏感级别"
            prop="deadlineLevel"
            required
            v-if="form.sensitiveDeadline === '2'"
          >
            <el-select v-model="form.deadlineLevel" placeholder="请选择">
              <el-option
                v-for="item in levelList"
                :key="item.levelCode"
                :label="item.levelName"
                :value="item.levelCode"
              />
            </el-select>
          </el-form-item>

          <!-- <div class="text-right w-100% mt-12px">
          <el-text>
            <el-icon>
              <Warning />
            </el-icon>
            审核通过“6月”后，敏感级别自动变更为“二级”
          </el-text>
        </div> -->
        </div>
        <div class="mt-16px">
          <SubTitle title="扩展字段内容" />
          <!-- <el-form label-width="100px" class="mt-12px" ref="extendForm"> -->
          <el-form-item
            v-for="(item, index) in extendList"
            :label="item.name"
            :prop="`field${item.index}`"
            :rules="[{ required: item.required == '1', message: `${item.name}不能为空` }]"
            :key="index"
          >
            <ns-input
              v-if="item.fillingMethod == '输入框'"
              v-model="form[`field${item.index}`]"
              clearable
              placeholder="请输入"
              style="width: 200px"
            />
            <el-select
              v-if="item.fillingMethod == '选择器'"
              clearable
              v-model="form[`field${item.index}`]"
              placeholder="请选择"
            >
              <el-option
                v-for="(option, optionIndex) in item.presetContentMap"
                :key="optionIndex"
                :label="option"
                :value="option"
              />
            </el-select>
          </el-form-item>
          <!-- </el-form> -->
        </div>
      </el-form>
      <div
        class="mt-32px"
        v-if="isPending == '1' || route.path == '/asset/pendingAsset/pendingFile'"
      >
        <SubTitle title="复核结果信息" />
        <el-form-item required label="复核状态：">
          <span v-if="props.params.recheckStatus == '1'">通过</span>
          <span v-else-if="props.params.recheckStatus == '0'">不通过</span>
          <span v-else>--</span>
        </el-form-item>
        <el-form-item required label="复核分类分级意见：">
          <div class="ml-auto">
            <el-button link type="primary" @click="applyRecheck">应用复核意见</el-button>
          </div>
        </el-form-item>
        <el-card shadow="never">
          <el-descriptions :column="recheckOptions.column">
            <el-descriptions-item
              :label="item.label"
              v-for="(item, index) in recheckOptions.columns"
              :key="index"
            >
              <span v-if="item.key == 'recheckSensitiveDeadline'">
                {{ props.params.recheckSensitiveDeadline == '2' ? '指定期限' : '默认期限' }}
              </span>
              <span v-else-if="item.key == 'recheckDeadlineTimeNum'">
                {{ props.params.recheckDeadlineTimeNum || '--' }}
                {{ props.params.recheckDeadlineTimeUnit || '--' }}
              </span>
              <span v-else>
                {{ props.params[item.key] || '--' }}
              </span>
            </el-descriptions-item>
            <div v-if="recheckExtendList">
              <el-descriptions-item
                :label="`${item.name}:`"
                v-for="(item, index) in extendList"
                :key="index"
                >{{ recheckExtendList[`recheckField${item.index}`] || '--' }}</el-descriptions-item
              >
            </div>
          </el-descriptions>
        </el-card>
        <el-form-item required label="复核说明：">
          {{ props.params.recheckDesc }}
        </el-form-item>
      </div>
    </div>
    <div>
      <el-button type="primary" @click="confirm">确定</el-button>
      <el-button @click="closeOutDrawer">取消</el-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { Warning, Plus, Minus } from '@element-plus/icons-vue'
import SubTitle from '@/components/SubTitle/index.vue'
import { assetUpdateLevel } from '@/api/assetDetail'
import { infoPage } from '@/api/dataStandards/info/index'
import { classificationTree } from '@/api/dataStandards/classification/index'
import { levelPage } from '@/api/strategyManage/level/index'
const message = useMessage() // 消息弹窗
const { proxy } = getCurrentInstance() as any
const route = useRoute()
const isPending = ref<string>(route.query.isPending as string)
console.log('route', route)
const formRef = ref()
const cascaderRef = ref()
const props = defineProps({
  params: {
    type: Object,
    default: () => {}
  },
  closeOutDrawer: Function
})
const classificationCascaderProps = ref({
  checkStrictly: true,
  label: 'cnName',
  value: 'id',
  children: 'children',
  emitPath: false
})

const form = ref({
  id: '',
  handClassification: '',
  handLevel: '',
  handImportance: '公开数据',
  sensitiveDeadline: '1',
  deadlineLevel: '',
  // extendContent: '',
  deadlineTimeNum: '',
  deadlineTimeUnit: ''
})
const rules = {
  sensitiveDeadline: [{ required: true, message: '敏感期限不能为空', trigger: 'change' }],
  deadlineTimeNum: [{ required: true, message: '时长不能为空', trigger: 'blur' }],
  deadlineTimeUnit: [{ required: true, message: '时间单位不能为空', trigger: 'blur' }],
  deadlineLevel: [{ required: true, message: '到期后敏感级别不能为空', trigger: 'blur' }],
  handClassification: [{ required: true, message: '分类不能为空', trigger: 'blur' }],
  handLevel: [{ required: true, message: '分级不能为空', trigger: 'blur' }]
}

const timeUnitOptions = [
  {
    label: '年',
    value: '年'
  },
  {
    label: '月',
    value: '月'
  },
  {
    label: '日',
    value: '日'
  }
]

const descInfo = reactive({
  column: 1,
  columns: [
    { label: '表名称：', key: 'table' },
    { label: '表描述：', key: 'remark' },
    { label: '所属库：', key: 'database' }
  ],
  data: {}
})

const tableData = [
  {
    title: '自动生成'
  },
  {
    title: '手动调整'
  }
]

const extendList = ref([
  {
    index: '1',
    name: '',
    required: '',
    fillingMethod: '输入框',
    presetContentMap: []
  }
])

const recheckOptions = reactive({
  column: 1,
  columns: [
    { label: '分类意见：', key: 'recheckClassificationName' },
    { label: '分级意见：', key: 'recheckLevelName' },
    { label: '重要程度：', key: 'recheckImportance' },
    { label: '敏感期限：', key: 'recheckSensitiveDeadline' },
    { label: '到期时间：', key: 'recheckDeadlineTimeNum' },
    { label: '到期后级别：', key: 'recheckDeadlineLevelName' }
  ],
  data: {}
})

const recheckExtendList = ref()

const applyRecheck = () => {
  form.value.handClassification = props.params.recheckClassification
  form.value.handLevel = props.params.recheckLevel
  form.value.handImportance = props.params.recheckImportance
  form.value.sensitiveDeadline = props.params.recheckSensitiveDeadline
  form.value.deadlineTimeNum = props.params.recheckDeadlineTimeNum
  form.value.deadlineTimeUnit = props.params.recheckDeadlineTimeUnit
  form.value.deadlineLevel = props.params.recheckDeadlineLevel
  for (let i = 1; i <= 20; i++) {
    form.value[`field${i}`] = recheckExtendList.value[`recheckField${i}`]
  }
}

const confirm = async () => {
  console.log('form.value', form.value)
  // 扩展字段
  formRef.value.validate(async (valid) => {
    if (valid) {
      const data = await assetUpdateLevel(form.value)
      console.log('data', data)
      if (data) {
        message.success('修改成功')
        props.params.callBack()
        props.closeOutDrawer()
      }
    }
  })
}

const classificationChange = (e) => {
  console.log('e', e)
  if (e) {
    const checkedNode = cascaderRef.value.getCheckedNodes()
    if (checkedNode[0].data.levelCode) {
      form.value.handLevel = checkedNode[0].data.levelCode
    }
  }
}

watch(
  () => form.value.handLevel,
  (newValue) => {
    console.log('newValue', newValue)
    const levelItem = levelList.value.find((item) => item.levelCode == newValue)
    console.log('levelItem', levelItem)
    if (levelItem) {
      form.value.handImportance = levelItem.importance
    }
  }
)

// 获取模板扩展字段列表
const getInfoList = async () => {
  const data = await infoPage({
    page: 1,
    pageSize: 20,
    dataStandardId: props.params.template,
    display: '1'
  })
  extendList.value = data.map((item) => {
    return {
      ...item,
      presetContentMap: item.presetContent ? JSON.parse(item.presetContent) : []
    }
  })
}

// 获取模板下的分类树
const classificationList = ref([])
const getClassificationTree = async () => {
  const data = await classificationTree({
    standardId: props.params.template
  })
  classificationList.value = data
}

// 获取等级下拉列表
const levelList = ref([])
const getLevelList = async () => {
  const { data } = await levelPage({ page: 1, pageSize: 999 })
  console.log('data', data)
  levelList.value = data
}

const openSample = () => {
  if (props.params.dataType === 'column') {
    proxy?.$Drawer({
      params: {
        samples: props.params.samples
      },
      title: `查看抽样数据`,
      size: '30%',
      component: import('@/views/asset/assetList/components/columnSamples.vue')
    })
  } else if (props.params.dataType === 'file') {
    proxy?.$Drawer({
      params: props.params,
      title: `查看抽样数据`,
      size: '30%',
      component: import('@/views/asset/assetList/components/fileSamples.vue')
    })
  } else if (props.params.dataType === 'table') {
    proxy?.$Drawer({
      params: props.params,
      title: `查看字段分级`,
      size: '30%',
      component: import('@/views/asset/assetList/components/tableSamples.vue')
    })
  }
}

onMounted(() => {
  getInfoList()
  getClassificationTree()
  getLevelList()
  descInfo.data = props.params
  if (props.params.recheckExtendContent) {
    recheckExtendList.value = JSON.parse(props.params.recheckExtendContent)
  }
  form.value = props.params
  if (!form.value.sensitiveDeadline) {
    form.value.sensitiveDeadline = '1'
  }
  if (props.params.dataType === 'column') {
    descInfo.column = 2
    descInfo.columns = [
      { label: '字段名称：', key: 'column' },
      { label: '字段类型：', key: 'columnType' },
      { label: '字段描述：', key: 'comment' },
      { label: '所属表：', key: 'table' },
      { label: '所属schema：', key: 'schema' },
      { label: '所属库：', key: 'database' }
    ]
  } else if (props.params.dataType === 'file') {
    descInfo.column = 1
    descInfo.columns = [
      { label: '文件名称：', key: 'fileName' },
      { label: '文件类型：', key: 'fileType' },
      { label: '文件指纹：', key: 'fileFingerprint' },
      // { label: '敏感等级：', key: 'levelName' },
      { label: '归属机构：', key: 'deptName' },
      { label: '归属系统：', key: 'sysName' },
      { label: '数据标准：', key: 'templateName' }
      // { label: '分类分级方式：', key: 'classificationWay' }
    ]
  }
})
</script>

<style scoped lang="scss">
:deep(.el-table .el-form-item--default) {
  margin-bottom: 0 !important;
}
</style>
